<template>
  <div class="voice-call">
    <!-- 导航栏 -->
    <van-nav-bar
      title="🎙️ 伴伴AI语音通话"
      left-arrow
      @click-left="goBack"
      class="nav-bar"
    />

    <!-- 连接状态 -->
    <div v-if="callState === 'connecting'" class="connecting-state">
      <van-loading size="24px" vertical>连接中...</van-loading>
      <p>正在连接伴伴AI...</p>
    </div>

    <!-- 通话界面 -->
    <div v-else-if="callState === 'connected'" class="call-interface">
      <!-- 语音动画区域 -->
      <div class="voice-hero">
        <div class="voice-animation" :class="{ speaking: isSpeaking, agent_speaking: agentSpeaking }">
          <div class="wave-circle"></div>
          <div class="wave-circle"></div>
          <div class="wave-circle"></div>
          <div class="microphone-icon">🎙️</div>
        </div>
      </div>

      <!-- 当前字幕显示 - 参考React版本的简洁设计 -->
      <div v-if="subtitleVisible && currentSubtitle && currentSubtitle.text" class="subtitle-display">
        <div class="subtitle-inner">
          <div class="subtitle-source">
            <div v-if="currentSubtitle.source === 'agent'" class="agent-icon">🤖</div>
            <div v-else class="user-icon">👤</div>
          </div>
          <div class="subtitle-text">{{ currentSubtitle.text }}</div>
        </div>
      </div>

      <!-- 字幕历史列表 -->
      <div v-if="subtitleVisible" class="chat-container">
        <div class="chat-header">
          <h3>💬 对话历史</h3>
          <div class="header-right">
            <span class="status-indicator">
              <span v-if="isSpeaking" class="status-dot speaking">🎤</span>
              <span v-else-if="agentSpeaking" class="status-dot agent-speaking">🤖</span>
              <span v-else class="status-dot listening">👂</span>
              {{ getStatusText() }}
            </span>
            <span class="chat-count">{{ subtitleHistory.length }} 条消息</span>
            <span class="scroll-hint">📜 可滚动</span>
          </div>
        </div>

        <div class="chat-messages" ref="chatMessagesRef">
          <div v-if="subtitleHistory.length === 0" class="empty-chat">
            <div class="empty-icon">🎤</div>
            <p>请开始说话，与伴伴AI对话...</p>
            <p class="empty-hint">支持实时语音识别和伴伴AI回复</p>
          </div>

          <div
            v-for="(message, index) in subtitleHistory"
            :key="`${message.source}-${message.sentenceId}`"
            :class="['message-item', message.source]"
          >
            <div class="message-content">
              <div class="message-text">{{ message.text }}</div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>
            <div class="message-avatar">
              {{ message.source === 'user' ? '👤' : '🤖' }}
            </div>
          </div>
        </div>

        <div class="chat-footer">
          <van-button size="small" @click="clearChat" type="default">
            🗑️ 清空对话
          </van-button>
          <van-button size="small" @click="scrollToBottom" type="primary">
            ⬇️ 滚动到底部
          </van-button>
        </div>
      </div>

      <!-- 控制按钮 -->
      <div class="control-buttons">
        <div class="control-item">
          <van-button
            :type="microphoneMuted ? 'default' : 'primary'"
            size="large"
            round
            @click="toggleMicrophone"
            class="control-btn"
          >
            {{ microphoneMuted ? '🔇' : '🎤' }}
          </van-button>
          <span class="control-label">{{ microphoneMuted ? '麦克风已关闭' : '麦克风已开启' }}</span>
        </div>

        <div class="control-item">
          <van-button
            type="danger"
            size="large"
            round
            @click="endCall"
            class="control-btn end-call"
          >
            📞
          </van-button>
          <span class="control-label">挂断通话</span>
        </div>

        <div class="control-item">
          <van-button
            :type="subtitleVisible ? 'primary' : 'default'"
            size="large"
            round
            @click="toggleSubtitle"
            class="control-btn"
          >
            {{ subtitleVisible ? '📝' : '📝' }}
          </van-button>
          <span class="control-label">{{ subtitleVisible ? '字幕已开启' : '字幕已关闭' }}</span>
        </div>

        <div class="control-item">
          <van-button
            type="default"
            size="large"
            round
            @click="toggleSettings"
            class="control-btn"
          >
            ⚙️
          </van-button>
          <span class="control-label">通话设置</span>
        </div>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="callState === 'error'" class="error-state">
      <div class="error-icon">❌</div>
      <h3>连接失败</h3>
      <p>{{ callErrorMessage || '无法连接到伴伴AI，请稍后重试' }}</p>
      <div class="error-details">
        <p>可能的原因：</p>
        <ul>
          <li>后端服务未启动或配置错误</li>
          <li>网络连接问题</li>
          <li>智能体服务配置问题</li>
        </ul>
      </div>
      <van-button type="primary" @click="startCall">重新连接</van-button>
    </div>

    <!-- 初始状态 -->
    <div v-else class="initial-state">
      <div class="welcome-content">
        <div class="ai-icon">🤖</div>
        <h2>AI语音助手</h2>
        <p>与真实的伴伴AI进行语音对话</p>
        <p class="demo-note">点击开始通话，系统将自动生成智能体并建立连接</p>

        <div class="action-buttons">
          <van-button type="primary" size="large" @click="startCall" :loading="loading">
            {{ loading ? '连接中...' : '开始通话' }}
          </van-button>
        </div>
      </div>
    </div>

    <!-- 设置弹窗 -->
    <van-popup v-model:show="showSettings" position="bottom" round>
      <div class="settings-panel">
        <h3>通话设置</h3>

        <van-cell-group>
          <van-cell title="智能打断" :value="enableVoiceInterrupt ? '开启' : '关闭'">
            <template #right-icon>
              <van-switch v-model="enableVoiceInterrupt" @change="updateVoiceInterrupt" />
            </template>
          </van-cell>

          <van-cell title="对讲模式" :value="enablePushToTalk ? '开启' : '关闭'">
            <template #right-icon>
              <van-switch v-model="enablePushToTalk" @change="updatePushToTalk" />
            </template>
          </van-cell>
        </van-cell-group>

        <div class="settings-actions">
          <van-button type="primary" @click="showSettings = false">确定</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'
import ARTCAICallEngine, {
  AICallAgentType,
  AICallState,
  AICallAgentState,
  AICallAgentConfig
} from 'aliyun-auikit-aicall'
import aiService from '@/services/aiService'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const callState = ref<'none' | 'connecting' | 'connected' | 'error'>('none')
const callErrorMessage = ref('')
const agentState = ref<AICallAgentState>(AICallAgentState.Listening)
const isSpeaking = ref(false)
const agentSpeaking = ref(false)
const microphoneMuted = ref(false)
const enableVoiceInterrupt = ref(true)
const enablePushToTalk = ref(false)
const showSettings = ref(false)

// 字幕相关 - 参考React版本的数据结构
const currentSubtitle = ref<{
  source: 'user' | 'agent'
  text: string
  timestamp: number
  sentenceId: number
  end: boolean
} | null>(null)

const subtitleHistory = ref<Array<{
  source: 'user' | 'agent'
  text: string
  timestamp: number
  sentenceId: number
  end: boolean
}>>([])

const showSubtitleDialog = ref(false)
const subtitleVisible = ref(true)  // 字幕显示开关
const chatMessagesRef = ref<HTMLElement>()  // 聊天消息容器引用

// AI通话引擎实例
let callEngine: any = null

// 返回上一页
const goBack = () => {
  if (callState.value === 'connected') {
    showDialog({
      title: '确认退出',
      message: '正在通话中，确定要退出吗？',
      confirmButtonText: '退出',
      cancelButtonText: '取消'
    }).then(() => {
      endCall()
      router.back()
    }).catch(() => {
      // 用户取消
    })
  } else {
    router.back()
  }
}

// 删除测试API连接功能

// 开始通话
const startCall = async () => {
  loading.value = true
  callState.value = 'connecting'

  try {
    // 1. 首先请求麦克风权限
    console.log('请求麦克风权限...')
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
      console.log('麦克风权限获取成功')
      // 立即停止流，我们只是为了获取权限
      stream.getTracks().forEach(track => track.stop())
    } catch (permissionError) {
      console.error('麦克风权限获取失败:', permissionError)
      showDialog({
        title: '麦克风权限',
        message: '需要麦克风权限才能进行语音通话，请允许访问麦克风'
      })
      callState.value = 'error'
      loading.value = false
      return
    }

    // 2. 检查浏览器支持
    const supportedResult = await ARTCAICallEngine.isSupported()
    if (!supportedResult.support) {
      showDialog({
        title: '不支持',
        message: '您的浏览器不支持WebRTC，请使用Chrome或Safari浏览器'
      })
      callState.value = 'error'
      loading.value = false
      return
    }

    // 生成用户ID
    const userId = `user_${Date.now()}`
    console.log('开始语音通话，用户ID:', userId)

    // 1. 生成伴伴AI - 使用真实的智能体ID
    console.log('正在生成伴伴AI...')
    const agentResponse = await aiService.generateAIAgentCall(userId, '8ed6ed9e6c57469e889a1bc3651ac64b', 'cn-beijing')

    if (agentResponse.code !== 200) {
      throw new Error(`生成伴伴AI失败: ${agentResponse.message}`)
    }

    const agentInfo = agentResponse.data || agentResponse
    console.log('伴伴AI生成成功:', agentInfo)

    // 提取智能体信息
    const instanceId = agentInfo.ai_agent_instance_id
    const channelId = agentInfo.channel_id
    const rtcAuthToken = agentInfo.rtc_auth_token
    const agentUserId = agentInfo.ai_agent_user_id

    // 2. 创建AI通话引擎
    callEngine = new ARTCAICallEngine()

    // 3. 配置伴伴AI - 尝试创建AICallAgentConfig实例
    let agentConfig
    try {
      agentConfig = new AICallAgentConfig()
      agentConfig.agentVoiceId = 'zhixiaoxia'
      agentConfig.enablePushToTalk = enablePushToTalk.value
      // 创建带有toJSON方法的interruptConfig对象
      agentConfig.interruptConfig = {
        enableVoiceInterrupt: enableVoiceInterrupt.value,
        toJSON: function() {
          return {
            enableVoiceInterrupt: this.enableVoiceInterrupt
          }
        }
      }
      // 创建带有toJSON方法的ttsConfig对象
      agentConfig.ttsConfig = {
        agentVoiceId: 'zhixiaoxia',
        toJSON: function() {
          return {
            agentVoiceId: this.agentVoiceId
          }
        }
      }

      // 配置创建成功

      // 如果没有toJSON方法，添加一个
      if (typeof agentConfig.toJSON !== 'function') {
        agentConfig.toJSON = function() {
          return {
            agentVoiceId: this.agentVoiceId,
            enablePushToTalk: this.enablePushToTalk,
            interruptConfig: this.interruptConfig,
            ttsConfig: this.ttsConfig
          }
        }
      }
    } catch (error) {
      console.error('创建AICallAgentConfig失败，使用普通对象:', error)
      // 如果类创建失败，使用普通对象
      agentConfig = {
        agentVoiceId: 'zhixiaoxia',
        enablePushToTalk: enablePushToTalk.value,
        interruptConfig: {
          enableVoiceInterrupt: enableVoiceInterrupt.value,
          toJSON: function() {
            return {
              enableVoiceInterrupt: this.enableVoiceInterrupt
            }
          }
        },
        ttsConfig: {
          agentVoiceId: 'zhixiaoxia',
          toJSON: function() {
            return {
              agentVoiceId: this.agentVoiceId
            }
          }
        },
        toJSON: function() {
          return {
            agentVoiceId: this.agentVoiceId,
            enablePushToTalk: this.enablePushToTalk,
            interruptConfig: this.interruptConfig,
            ttsConfig: this.ttsConfig
          }
        }
      }
    }

    // 4. 引擎配置
    const engineConfig = {
      rtcEngineConfig: {
        environment: 'PROD' as const
      }
    }

    // 5. 通话配置
    const callConfig = {
      agentType: AICallAgentType.VoiceAgent,
      region: 'cn-beijing',
      userId: userId,
      userJoinToken: rtcAuthToken,
      agentConfig,
      agentId: instanceId,
      userData: JSON.stringify({ channelId, agentUserId })
    }

    console.log('通话配置:', callConfig)
    console.log('agentConfig类型:', typeof callConfig.agentConfig)
    console.log('agentConfig.toJSON:', typeof callConfig.agentConfig?.toJSON)

    // 6. 设置事件监听
    setupEventListeners()

    // 7. 初始化引擎
    console.log('正在初始化通话引擎...')
    await callEngine.init(AICallAgentType.VoiceAgent, engineConfig)
    console.log('引擎初始化成功')

    // 8. 启动通话 - 使用callWithConfig方法（类似ProxyController）
    console.log('正在启动通话...')

    // 重新构建callConfig，确保包含所有必需的属性
    const originalAgentId = '8ed6ed9e6c57469e889a1bc3651ac64b'  // 使用原始的智能体ID
    const finalCallConfig = {
      agentType: AICallAgentType.VoiceAgent,
      region: 'cn-beijing',
      userId: userId,  // 这是真实用户的ID
      userJoinToken: rtcAuthToken,
      agentConfig: agentConfig,
      agentId: originalAgentId,  // 使用原始智能体ID，不是实例ID
      userData: JSON.stringify({
        channelId: channelId,
        agentUserId: agentUserId,
        instanceId: instanceId  // 实例ID放在userData中
      })
    }

    // 配置验证完成

    // 使用callWithConfig方法
    await callEngine.callWithConfig(finalCallConfig)
    console.log('通话启动成功')

  } catch (error) {
    console.error('启动通话失败:', error)
    callState.value = 'error'
    callErrorMessage.value = `启动通话失败: ${error.message || '未知错误'}`
    showToast({
      type: 'fail',
      message: '启动通话失败'
    })
  } finally {
    loading.value = false
  }
}

// 设置事件监听
const setupEventListeners = () => {
  if (!callEngine) return

  // 智能体启动事件
  callEngine.on('agentStarted', (agentInfo: any) => {
    console.log('智能体启动成功:', agentInfo)
  })

  // 通话开始事件
  callEngine.on('callBegin', () => {
    console.log('通话开始')
    callState.value = 'connected'
    showToast({
      type: 'success',
      message: '连接成功'
    })
  })

  // 通话结束事件
  callEngine.on('callEnd', () => {
    console.log('通话结束')
    callState.value = 'none'
  })

  // 错误事件
  callEngine.on('error', (error: any) => {
    console.error('通话错误:', error)
    callState.value = 'error'
    callErrorMessage.value = '通话出现错误'
  })

  // 智能体状态变化 - 监听多种可能的事件
  callEngine.on('agentStateChanged', (newState: AICallAgentState) => {
    console.log('智能体状态变化:', newState)
    agentState.value = newState
    agentSpeaking.value = newState === AICallAgentState.Speaking
  })

  // 监听其他可能的状态事件
  callEngine.on('AICallAgentStateChanged', (newState: AICallAgentState) => {
    console.log('伴伴AI状态变化:', newState)
    agentState.value = newState
    agentSpeaking.value = newState === AICallAgentState.Speaking
  })

  // 监听智能体开始说话事件
  callEngine.on('agentStartSpeaking', () => {
    console.log('智能体开始说话')
    agentState.value = AICallAgentState.Speaking
    agentSpeaking.value = true
  })

  // 监听智能体停止说话事件
  callEngine.on('agentStopSpeaking', () => {
    console.log('智能体停止说话')
    agentState.value = AICallAgentState.Listening
    agentSpeaking.value = false
  })

  // 音量变化（用于检测说话状态）
  callEngine.on('activeSpeakerVolumeChanged', (userId: string, volume: number) => {
    if (userId === '') {
      // 本地用户说话状态
      isSpeaking.value = volume > 30
    }
  })

  // 删除不需要的状态跟踪变量

  // AI字幕监听 - 参考React版本的智能合并逻辑
  callEngine.on('agentSubtitleNotify', (subtitleData: any) => {
    let subtitle = null

    // 处理不同的数据格式
    if (Array.isArray(subtitleData) && subtitleData.length > 0) {
      subtitle = subtitleData[0]
    } else if (subtitleData && typeof subtitleData === 'object') {
      subtitle = subtitleData
    } else {
      return
    }

    if (subtitle && subtitle.sentenceId !== undefined) {
      updateSubtitle({
        data: subtitle,
        source: 'agent'
      })
    }
  })

  // 用户字幕监听 - 参考React版本的处理逻辑
  callEngine.on('userSubtitleNotify', (subtitleData: any) => {
    let subtitle = null

    // 处理不同的数据格式
    if (Array.isArray(subtitleData) && subtitleData.length > 0) {
      subtitle = subtitleData[0]
    } else if (subtitleData && typeof subtitleData === 'object') {
      subtitle = subtitleData
    } else {
      return
    }

    if (subtitle && subtitle.sentenceId !== undefined) {
      updateSubtitle({
        data: subtitle,
        source: 'user'
      })
    }
  })

  // 移除调试事件监听器

  // 移除备用事件监听器

  // 参考React版本的字幕更新逻辑
  const updateSubtitle = (subtitle: { data: any, source: 'user' | 'agent' }) => {
    const existSubtitleIndex = subtitleHistory.value.findIndex(
      (item) => item.sentenceId === subtitle.data.sentenceId && item.source === subtitle.source
    )

    // 字幕已经存在，更新内容
    if (existSubtitleIndex > -1) {
      const existSubtitle = subtitleHistory.value[existSubtitleIndex]
      if (subtitle.source === 'agent') {
        // AI字幕累积文本
        subtitle.data.text = existSubtitle.text + subtitle.data.text
      }

      // 更新现有字幕
      subtitleHistory.value[existSubtitleIndex] = {
        source: subtitle.source,
        text: subtitle.data.text,
        timestamp: Date.now(),
        sentenceId: subtitle.data.sentenceId,
        end: subtitle.data.end
      }

      // 触发响应式更新
      subtitleHistory.value = [...subtitleHistory.value]
    } else if (subtitle.data.text) {
      // 新字幕，添加到列表
      const newSubtitle = {
        source: subtitle.source,
        text: subtitle.data.text,
        timestamp: Date.now(),
        sentenceId: subtitle.data.sentenceId,
        end: subtitle.data.end
      }

      subtitleHistory.value = [...subtitleHistory.value, newSubtitle]
    }

    // 更新当前字幕
    if (subtitle.data.text) {
      currentSubtitle.value = {
        source: subtitle.source,
        text: subtitle.data.text,
        timestamp: Date.now(),
        sentenceId: subtitle.data.sentenceId,
        end: subtitle.data.end
      }
    }

    // 保持历史记录在合理范围内
    if (subtitleHistory.value.length > 100) {
      subtitleHistory.value = subtitleHistory.value.slice(-100)
    }

    nextTick(() => {
      scrollToBottom()
    })
  }

  // 处理字幕的通用函数（保留用于测试）
  const handleSubtitle = (subtitle: any, source?: 'user' | 'agent') => {
    if (subtitle && subtitle.text) {
      const subtitleItem = {
        source: source || (subtitle.userId ? 'user' : 'agent'),
        text: subtitle.text,
        timestamp: Date.now(),
        sentenceId: Date.now(), // 临时ID
        end: true
      }

      subtitleHistory.value = [...subtitleHistory.value, subtitleItem]
      currentSubtitle.value = subtitleItem

      nextTick(() => {
        scrollToBottom()
      })
    }
  }

  // 自动播放失败处理
  callEngine.on('autoPlayFailed', () => {
    showDialog({
      title: '音频自动播放失败',
      message: '请点击确认按钮恢复播放',
      confirmButtonText: '确认'
    })
  })
}

// 结束通话
const endCall = () => {
  if (callEngine) {
    try {
      callEngine.handup()
      console.log('通话已挂断')
    } catch (error) {
      console.error('挂断通话失败:', error)
    }
    callEngine = null
  }
  callState.value = 'none'
  currentSubtitle.value = null
}

// 切换麦克风
const toggleMicrophone = async () => {
  if (callEngine) {
    microphoneMuted.value = !microphoneMuted.value
    try {
      // 尝试多种可能的API方法
      if (typeof callEngine.mute === 'function') {
        await callEngine.mute(microphoneMuted.value)
      } else if (typeof callEngine.muteLocalMic === 'function') {
        await callEngine.muteLocalMic(microphoneMuted.value)
      } else if (typeof callEngine.enableMicrophone === 'function') {
        await callEngine.enableMicrophone(!microphoneMuted.value)
      } else {
        console.warn('未找到麦克风控制方法')
      }

      // 如果是开启麦克风，重新请求权限
      if (!microphoneMuted.value) {
        try {
          const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
          console.log('麦克风重新激活成功')
          // 不要立即停止流，让引擎使用
        } catch (error) {
          console.error('麦克风激活失败:', error)
          microphoneMuted.value = true // 回滚状态
          showToast({
            type: 'fail',
            message: '麦克风激活失败'
          })
          return
        }
      }

      showToast({
        type: 'success',
        message: microphoneMuted.value ? '麦克风已关闭' : '麦克风已开启'
      })
    } catch (error) {
      console.error('切换麦克风失败:', error)
      showToast({
        type: 'fail',
        message: '操作失败'
      })
    }
  }
}

// 切换字幕显示
const toggleSubtitle = () => {
  subtitleVisible.value = !subtitleVisible.value
  showToast({
    type: 'success',
    message: subtitleVisible.value ? '字幕已开启' : '字幕已关闭'
  })
}

// 切换设置面板
const toggleSettings = () => {
  showSettings.value = !showSettings.value
}

// 获取状态文本
const getStatusText = () => {
  if (isSpeaking.value) {
    return '正在说话'
  } else if (agentSpeaking.value) {
    return 'AI回复中'
  } else {
    return '等待中'
  }
}

// 格式化时间
const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatMessagesRef.value) {
      chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
    }
  })
}

// 删除测试消息功能

// 清空聊天记录
const clearChat = () => {
  showDialog({
    title: '确认清空',
    message: '确定要清空所有对话记录吗？',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    subtitleHistory.value = []
    currentSubtitle.value = null
    showToast({
      type: 'success',
      message: '对话记录已清空'
    })
  }).catch(() => {
    // 用户取消
  })
}

// 显示字幕历史
const showSubtitleHistory = () => {
  if (subtitleHistory.value.length === 0) {
    showToast('暂无对话记录')
    return
  }

  const historyText = subtitleHistory.value
    .map(item => {
      const time = new Date(item.timestamp).toLocaleTimeString()
      const speaker = item.source === 'user' ? '您' : 'AI'
      return `[${time}] ${speaker}：${item.text}`
    })
    .join('\n\n')

  showDialog({
    title: '对话历史',
    message: historyText,
    confirmButtonText: '确定'
  })
}

// 更新语音打断设置
const updateVoiceInterrupt = (value: boolean) => {
  if (callEngine) {
    try {
      // 检查是否有这个方法
      if (typeof callEngine.enableVoiceInterrupt === 'function') {
        callEngine.enableVoiceInterrupt(value)
      } else {
        console.warn('enableVoiceInterrupt方法不存在')
      }
      showToast({
        type: 'success',
        message: value ? '智能打断已开启' : '智能打断已关闭'
      })
    } catch (error) {
      console.error('设置语音打断失败:', error)
      showToast({
        type: 'fail',
        message: '设置失败'
      })
    }
  }
}

// 更新对讲模式设置
const updatePushToTalk = (value: boolean) => {
  if (callEngine) {
    try {
      // 检查是否有这个方法
      if (typeof callEngine.enablePushToTalk === 'function') {
        callEngine.enablePushToTalk(value)
      } else {
        console.warn('enablePushToTalk方法不存在')
      }
      showToast({
        type: 'success',
        message: value ? '对讲模式已开启' : '对讲模式已关闭'
      })
    } catch (error) {
      console.error('设置对讲模式失败:', error)
      showToast({
        type: 'fail',
        message: '设置失败'
      })
    }
  }
}

// 组件卸载时清理
onUnmounted(() => {
  if (callEngine) {
    callEngine.handup()
    callEngine = null
  }
})

// 页面离开前确认
onMounted(() => {
  const beforeUnload = (e: BeforeUnloadEvent) => {
    if (callState.value === 'connected') {
      e.preventDefault()
      e.returnValue = ''
    }
  }
  window.addEventListener('beforeunload', beforeUnload)

  onUnmounted(() => {
    window.removeEventListener('beforeunload', beforeUnload)
  })
})
</script>

<style scoped>
.voice-call {
  min-height: 100vh;
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 50%, #fecfef 100%);
  position: relative;
  overflow: hidden;
}

.voice-call::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background:
    radial-gradient(circle at 20% 80%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(255, 255, 255, 0.1) 0%, transparent 50%);
  pointer-events: none;
  animation: float 6s ease-in-out infinite;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-10px);
  }
}

/* 页面加载动画 */
.voice-call {
  animation: page-fade-in 0.8s ease-out;
}

@keyframes page-fade-in {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 增强的波纹效果 */
@keyframes wave {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  100% {
    transform: scale(2);
    opacity: 0;
  }
}

  .nav-bar {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    position: relative;
    z-index: 10;
  }

  .connecting-state,
  .error-state,
  .initial-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 80vh;
    padding: 40px 20px;
    color: #2c3e50;
    text-align: center;
    position: relative;
    z-index: 5;

    .error-icon,
    .ai-icon {
      font-size: 64px;
      margin-bottom: 20px;
      animation: bounce 2s infinite;
      filter: drop-shadow(0 0 20px rgba(255, 255, 255, 0.5));
    }

    @keyframes bounce {
      0%, 20%, 50%, 80%, 100% {
        transform: translateY(0);
      }
      40% {
        transform: translateY(-10px);
      }
      60% {
        transform: translateY(-5px);
      }
    }

    h2, h3 {
      margin: 0 0 16px 0;
      font-size: 24px;
    }

    p {
      margin: 0 0 16px 0;
      font-size: 16px;
      opacity: 0.9;
    }

    .demo-note {
      font-size: 14px;
      opacity: 0.7;
      margin-bottom: 32px !important;
    }

    .action-buttons {
      display: flex;
      flex-direction: column;
      gap: 12px;
      width: 100%;
      max-width: 300px;
    }

    .error-details {
      background: rgba(255, 255, 255, 0.1);
      border-radius: 8px;
      padding: 16px;
      margin: 16px 0;
      text-align: left;

    }

    .initial-state p {
      margin: 0 0 8px 0;
      font-weight: bold;
    }

    .initial-state ul {
      margin: 0;
      padding-left: 20px;
    }

    .initial-state ul li {
      margin: 4px 0;
      font-size: 14px;
      opacity: 0.9;
    }
  }

  .call-interface {
    display: flex;
    flex-direction: column;
    min-height: 80vh;
    padding: 20px;
    position: relative;
    z-index: 5;

    .voice-hero {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 40px 0;

    }

    .voice-area .voice-animation {
      position: relative;
      width: 200px;
      height: 200px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .voice-animation .wave-circle {
      position: absolute;
      border: 2px solid rgba(255, 154, 158, 0.4);
      border-radius: 50%;
      animation: wave 2s infinite;
      box-shadow: 0 0 20px rgba(255, 154, 158, 0.2);
    }

    .wave-circle:nth-child(1) {
      width: 120px;
      height: 120px;
      animation-delay: 0s;
    }

    .wave-circle:nth-child(2) {
      width: 160px;
      height: 160px;
      animation-delay: 0.5s;
    }

    .wave-circle:nth-child(3) {
      width: 200px;
      height: 200px;
      animation-delay: 1s;

    }

    .voice-animation .microphone-icon {
      font-size: 48px;
      z-index: 10;
      color: #e74c3c;
      filter: drop-shadow(0 0 10px rgba(231, 76, 60, 0.5));
      animation: mic-glow 3s infinite;
    }

    @keyframes mic-glow {
      0%, 100% {
        filter: drop-shadow(0 0 10px rgba(231, 76, 60, 0.5));
      }
      50% {
        filter: drop-shadow(0 0 20px rgba(231, 76, 60, 0.8));
      }
    }

    .voice-animation.speaking .wave-circle {
      border-color: rgba(46, 204, 113, 0.6);
      animation-duration: 1s;
      box-shadow: 0 0 30px rgba(46, 204, 113, 0.4);
    }

    .voice-animation.agent_speaking .wave-circle {
      border-color: rgba(52, 152, 219, 0.6);
      animation-duration: 0.8s;
      box-shadow: 0 0 30px rgba(52, 152, 219, 0.4);
    }

    /* 当前字幕显示样式 - 参考React版本 */
    .subtitle-display {
      position: absolute;
      left: 0;
      right: 0;
      top: 20px;
      z-index: 4;
      display: flex;
      align-items: center;
      justify-content: center;
      pointer-events: none;

    }

    .subtitle-display .subtitle-inner {
      display: flex;
      align-items: flex-start;
      padding: 12px 16px;
      margin: 0 20px;
      background: rgba(255, 255, 255, 0.95);
      border-radius: 12px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      backdrop-filter: blur(10px);
      max-width: 80%;
      animation: subtitle-fade-in 0.3s ease-out;
      border: 1px solid rgba(255, 154, 158, 0.2);
    }

    @keyframes subtitle-fade-in {
      from {
        opacity: 0;
        transform: translateY(10px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }

    .subtitle-display .subtitle-source {
      width: 24px;
      margin-right: 8px;
      flex-shrink: 0;
    }

    .subtitle-source .agent-icon,
    .subtitle-source .user-icon {
      width: 24px;
      height: 24px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      background: #f5f5f5;
    }

    .subtitle-source .agent-icon {
      background: #e6f7ff;
    }

    .subtitle-source .user-icon {
      background: #f6ffed;
    }

    .subtitle-display .subtitle-text {
      flex: 1;
      font-size: 14px;
      line-height: 1.4;
      color: #333;
      text-align: left;
    }

    /* 聊天容器样式 */
    .chat-container {
      background: rgba(255, 255, 255, 0.95);
      border-radius: 16px;
      margin: 20px 0;
      height: 400px;
      display: flex;
      flex-direction: column;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

    }

    .chat-container .chat-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 20px;
      border-bottom: 1px solid #f0f0f0;
      background: rgba(255, 255, 255, 0.8);
      border-radius: 16px 16px 0 0;
    }

    .chat-header h3 {
      margin: 0;
      font-size: 18px;
      color: #333;
    }

    .chat-header .header-right {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .chat-header .status-indicator {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 12px;
      color: #666;
      background: #f8f9fa;
      padding: 4px 8px;
      border-radius: 12px;
    }

    .status-indicator .status-dot {
      font-size: 14px;
    }

    .status-dot.speaking {
      animation: pulse 1s infinite;
    }

    .status-dot.agent-speaking {
      animation: bounce 1s infinite;
    }

    .chat-header .chat-count {
      font-size: 12px;
      color: #999;
      background: #f5f5f5;
      padding: 4px 8px;
      border-radius: 12px;
    }

    .chat-header .scroll-hint {
      font-size: 11px;
      color: #666;
      background: rgba(255, 154, 158, 0.1);
      padding: 3px 6px;
      border-radius: 10px;
      border: 1px solid rgba(255, 154, 158, 0.2);
      animation: hint-pulse 3s infinite;
    }

    @keyframes hint-pulse {
      0%, 100% {
        opacity: 0.7;
      }
      50% {
        opacity: 1;
      }
    }

    .chat-container .chat-messages {
      flex: 1;
      overflow-y: auto;
      padding: 16px;
      display: flex;
      flex-direction: column;
      gap: 12px;
      height: 300px; /* 固定高度 */
      max-height: 300px;
      scroll-behavior: smooth; /* 平滑滚动 */
      position: relative;
    }

    /* 滚动渐变遮罩效果 */
    .chat-container .chat-messages::before {
      content: '';
      position: sticky;
      top: 0;
      left: 0;
      right: 0;
      height: 20px;
      background: linear-gradient(to bottom, rgba(255, 255, 255, 0.9), transparent);
      z-index: 1;
      pointer-events: none;
    }

    .chat-container .chat-messages::after {
      content: '';
      position: sticky;
      bottom: 0;
      left: 0;
      right: 0;
      height: 20px;
      background: linear-gradient(to top, rgba(255, 255, 255, 0.9), transparent);
      z-index: 1;
      pointer-events: none;
    }

    .chat-messages .empty-chat {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      color: #999;
    }

    .empty-chat .empty-icon {
      font-size: 48px;
      margin-bottom: 16px;
    }

    .empty-chat p {
      margin: 0 0 8px 0;
      font-size: 16px;
    }

    .empty-chat p.empty-hint {
      font-size: 14px;
      opacity: 0.7;
    }

    .chat-messages .message-item {
      display: flex;
      align-items: flex-end;
      gap: 12px;
      max-width: 80%;
    }

    .message-item.user {
      align-self: flex-end;
      flex-direction: row-reverse;
    }

    .message-item.user .message-content {
      background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
      color: white;
      border-radius: 18px 18px 4px 18px;
    }

    .message-item.agent {
      align-self: flex-start;
    }

    .message-item.agent .message-content {
      background: #f5f5f5;
      color: #333;
      border-radius: 18px 18px 18px 4px;
    }

    .message-item .message-content {
      padding: 12px 16px;
      max-width: 100%;
      word-wrap: break-word;
    }

    .message-content .message-text {
      font-size: 15px;
      line-height: 1.4;
      margin-bottom: 4px;
    }

    .message-content .message-time {
      font-size: 11px;
      opacity: 0.7;
      text-align: right;
    }

    .message-item .message-avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.9);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      flex-shrink: 0;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    /* 滚动条样式 - 贴合主题 */
    .chat-messages::-webkit-scrollbar {
      width: 8px;
    }

    .chat-messages::-webkit-scrollbar-track {
      background: rgba(255, 255, 255, 0.3);
      border-radius: 4px;
      margin: 4px 0;
    }

    .chat-messages::-webkit-scrollbar-thumb {
      background: linear-gradient(135deg, #ff9a9e, #fecfef);
      border-radius: 4px;
      border: 1px solid rgba(255, 255, 255, 0.2);
    }

    .chat-messages::-webkit-scrollbar-thumb:hover {
      background: linear-gradient(135deg, #ff8a8e, #febfdf);
      box-shadow: 0 2px 8px rgba(255, 154, 158, 0.3);
    }

    .chat-container .chat-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 20px;
      border-top: 1px solid #f0f0f0;
      background: rgba(255, 255, 255, 0.8);
      border-radius: 0 0 16px 16px;
      gap: 12px;
    }

    .control-buttons {
      display: flex;
      justify-content: center;
      gap: 20px;
      padding: 20px 0;
      flex-wrap: wrap;

    .control-buttons .control-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 8px;
      min-width: 70px;
    }

    .control-item .control-btn {
      width: 60px;
      height: 60px;
      font-size: 24px;
      border-radius: 50%;
      border: 2px solid rgba(255, 255, 255, 0.3);
      background: rgba(255, 255, 255, 0.2);
      color: #2c3e50;
      transition: all 0.3s ease;
      backdrop-filter: blur(10px);
      box-shadow: 0 4px 15px rgba(255, 255, 255, 0.2);
      animation: btn-float 4s ease-in-out infinite;
    }

    .control-btn:hover {
      transform: translateY(-2px) scale(1.05);
      box-shadow: 0 6px 20px rgba(255, 255, 255, 0.3);
    }

    .control-btn:active {
      transform: translateY(0) scale(0.95);
    }

    .control-btn.end-call {
      background: linear-gradient(135deg, #e74c3c, #c0392b);
      border-color: #e74c3c;
      color: white;
      box-shadow: 0 4px 15px rgba(231, 76, 60, 0.3);
    }

    .control-btn.end-call:hover {
      box-shadow: 0 6px 20px rgba(231, 76, 60, 0.4);
    }

    @keyframes btn-float {
      0%, 100% {
        transform: translateY(0px);
      }
      50% {
        transform: translateY(-2px);
      }
    }

    .control-item .control-label {
      font-size: 11px;
      color: #2c3e50;
      text-align: center;
      white-space: nowrap;
      line-height: 1.2;
      font-weight: 500;
      opacity: 0.8;
    }
    }

    /* 响应式布局 */
    @media (max-width: 768px) {
      .chat-container {
        height: 350px;
        margin: 16px 0;
      }

      .chat-container .chat-header {
        padding: 12px 16px;
      }

      .chat-header h3 {
        font-size: 16px;
      }

      .chat-header .scroll-hint {
        display: none; /* 移动端隐藏滚动提示 */
      }

      .chat-container .chat-messages {
        padding: 12px;
      }

      .chat-messages .message-item {
        max-width: 85%;
      }

      .message-item .message-content {
        padding: 10px 14px;
      }

      .message-content .message-text {
        font-size: 14px;
      }

      .message-item .message-avatar {
        width: 28px;
        height: 28px;
        font-size: 14px;
      }

      .chat-container .chat-footer {
        padding: 10px 16px;
      }

      .control-buttons {
        gap: 15px;
      }

      .control-buttons .control-item {
        min-width: 60px;
      }

      .control-item .control-btn {
        width: 50px;
        height: 50px;
        font-size: 20px;
      }

      .control-item .control-label {
        font-size: 10px;
      }
    }

    @media (max-width: 480px) {
      .chat-container {
        height: 300px;
      }

      .chat-messages .message-item {
        max-width: 90%;
      }

      .message-item .message-content {
        padding: 8px 12px;
      }

      .message-content .message-text {
        font-size: 13px;
      }

      .message-item .message-avatar {
        width: 24px;
        height: 24px;
        font-size: 12px;
      }
    }
  }

  .settings-panel {
    padding: 20px;
  }

  .settings-panel h3 {
    margin: 0 0 20px 0;
    text-align: center;
  }

  .settings-panel .settings-actions {
    margin-top: 20px;
    text-align: center;
  }


</style>
